package top.meeting.room.module.book.model;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.date.format.DatePrinter;
import top.meeting.room.baseModel.BaseBook;
import top.meeting.room.common.constant.ResultEnum;
import top.meeting.room.common.exceptions.HandlerException;
import top.meeting.room.common.kit.TimeKit;
import top.meeting.room.module.book.dto.Timer;
import top.meeting.room.module.book.dto.WeekBookData;
import top.meeting.room.module.system.model.User;
import top.meeting.room.module.system.services.impl.UserService;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Lyt on 2017/9/11.
 */
public class Book extends BaseBook<Book> {
    public static final Book dao = new Book().dao();
    private static String[] weekDays = {"星期日", "星期六", "星期五", "星期四", "星期三", "星期二", "星期一"};

    /**
     * SqlParas And Caches
     */
    public static final String book_getModel = "book.getModel";
    public static final String book_pageModel = "book.pageModel";
    public static final String book_getRecord = "book.getRecord";
    public static final String book_modelList = "book.modelList";
    public static final String book_recordList = "book.recordList";
    public static final String book_pageRecord = "book.pageRecord";
    public static final String book_deleteByIds = "book.deleteByIds";
    public static final String book_user = "book.user";
    public static final String book_isApprove = "book.isApprove";
    public static final String book_isBook = "book.isBook";
    public static final String book_approver = "book.approver";
    public static final String book_findRecordByMe = "book.findRecordByMe";

    public String msgForBookUser(String msg) {
        StringBuffer stringBuffer = null;
        if ("预订结果".equals(msg)) {
            stringBuffer = new StringBuffer("会议室审批" + (this.getStatus() == 1 ? "通过" : "未通过") + ":\n")
                    .append(((this.getStatus() == 1) && StrKit.isBlank(this.getRefuse())) ? "" : "原因:" + this.getRefuse() + "\n")
                    .append("时间:" + DateUtil.format(this.getStartTime(), "yyyy-MM-dd HH:mm") + "-" + DateUtil.format(this.getEndTime(), "HH:mm") + "\n")
                    .append("目的:" + this.getReason());
        }
        if ("执行会议".equals(msg)) {
            stringBuffer = new StringBuffer("您有一场会议即将开始，请前往" + (this.getRoom() == 1L ? "大会议室\n" : "小会议室\n"))
                    .append(((this.getStatus() == 1) && StrKit.isBlank(this.getRefuse())) ? "" : "原因:" + this.getRefuse() + "\n")
                    .append("时间:" + DateUtil.format(this.getStartTime(), "yyyy-MM-dd HH:mm") + "-" + DateUtil.format(this.getEndTime(), "HH:mm") + "\n")
                    .append("目的:" + this.getReason());
        }
        if (this.getUser() != null)
            stringBuffer.append("\n")
                    .append("部门:" + this.getUser().getDepartment() + "\n")
                    .append("预订人:" + this.getUser().getRealName());
        if (this.getApprover() != null)
            stringBuffer.append("\n")
                    .append("审批人:" + this.getApprover().getRealName());
        return toSearch(stringBuffer);
    }

    public String msgForBookApprover(Long bookId, String msg) {
        StringBuffer stringBuffer = new StringBuffer(msg)
                .append("时间:" + DateUtil.format(this.getStartTime(), "yyyy-MM-dd HH:mm") + "-" + DateUtil.format(this.getEndTime(), "HH:mm") + "\n")
                .append("目的:" + this.getReason() + "\n")
                .append("会议室：" + (this.getRoom() == 1L ? "大会议室\n" : "小会议室\n"));
        if (this.getUser() != null)
            stringBuffer.append("\n")
                    .append("部门:" + this.getUser().getDepartment() + "\n")
                    .append("预订人:" + this.getUser().getRealName());
        return toCheck(stringBuffer, bookId);
    }

    private String toCheck(StringBuffer stringBuffer, Long bookId) {
        return stringBuffer.append("\n<a href='http://tmeet.1322.com/#/check?bookId=" + bookId + "'>查看详情</a>").toString();
    }

    private String toSearch(StringBuffer stringBuffer) {
        return stringBuffer.toString();
    }

    public User getUser() {
        if (this.getBookUser() == null) return null;
        User retVal = CacheKit.get(book_user, String.valueOf(this.getBookUser()));
        if (retVal == null) {
            retVal = UserService.me.getModel(this.getBookUser());
            CacheKit.put(book_user, String.valueOf(this.getBookUser()), retVal);
        }
        return retVal;
    }

    public User getApprover() {
        if (this.getBookApprover() == null) return null;
        User retVal = CacheKit.get(book_approver, String.valueOf(this.getBookApprover()));
        if (retVal == null) {
            retVal = UserService.me.getModel(this.getBookApprover());
            CacheKit.put(book_approver, String.valueOf(this.getBookApprover()), retVal);
        }
        return retVal;
    }

    public Record toDTO() {
        Record retVal = super.toRecord();
        User user = User.dao.findById(this.getBookUser());
        Date dateTime = new Date(this.getBookDate());
        int dayOfWeek = DateUtil.dayOfWeek(dateTime) - 1 == 0 ? 7 : DateUtil.dayOfWeek(dateTime) - 1;
        String startTimeSlot = null, endTimeSlot = null;
        if (this.getStartTime() != null) {
            startTimeSlot = DateUtil.format(this.getStartTime(), "HH:mm");
        }
        if (this.getEndTime() != null) {
            endTimeSlot = DateUtil.format(this.getEndTime(), "HH:mm");
        }
        return retVal.set("dayOfWeek", dayOfWeek)
                .set("timeSlot_start", startTimeSlot)
                .set("timeSlot_end", endTimeSlot)
                .set("book_userName", user == null ? "暂无" : user.getRealName())
                .set("book_userDept", user == null ? "暂无" : user.getDepartment())
                .set("bookOpenId", user == null ? "暂无" : user.getOpenId());

    }


    public Record toPendingApprovalBook() {
        Record record = this.toDTO();
        String date = record.get("start_time").toString().split(" ")[0];
        return record.set("book_time", date + " " + weekDays[7 - (int) record.get("dayOfWeek")] + " " + record.get("timeSlot_start") + "-" + record.get("timeSlot_end"))
                .keep("id", "reason", "book_userDept", "book_userName", "book_time", "is_ext","ext_num");
    }

    public Record toDeptBook() {
        Record record = this.toDTO();
        String date = record.get("start_time").toString().split(" ")[0];
        return record.set("bookWeek", weekDays[7 - (int) record.get("dayOfWeek")])
                .set("bookDate", date)
                .set("bookTime", record.get("timeSlot_start") + "-" + record.get("timeSlot_end"))
                .set(Book.status, record.get(Book.status))
                .set(Book.refuse, record.get(Book.refuse))
                .set(Book.bookUser, record.get(Book.bookUser))
                .keep(id, "bookWeek", "bookDate", "bookTime", "book_userDept", "reason", "book_userName", Book.status, Book.refuse, bookUser);
    }


//    public static List findAllHandler(List<Record> bookRecordList){
//        bookRecordList.forEach(record -> {
//            List dayData = getDayData(new HashMap(), record);
//        });
//    }

    public static List handlerFind(List<Record> bookRecordList) {
        if (bookRecordList == null || bookRecordList.size() == 0) return null;
        List dataList = new ArrayList();
        List<Map<String, String>> dataMap = new ArrayList<Map<String, String>>();
        for (int i = 0; i < 7; i++) {
            dataMap.add(new HashMap<String, String>());
        }
        WeekBookData monDataBean = new WeekBookData();
        WeekBookData tueDataBean = new WeekBookData();
        WeekBookData wenDataBean = new WeekBookData();
        WeekBookData thurDataBean = new WeekBookData();
        WeekBookData friDataBean = new WeekBookData();
        WeekBookData satDataBean = new WeekBookData();
        WeekBookData sunDataBean = new WeekBookData();
        for (Record bookRecord : bookRecordList) {
            int dayOfWeek = (int) bookRecord.get("dayOfWeek");
            String dayOfWeekStr = null;
            switch (dayOfWeek) {
                case 1:
                    dayOfWeekStr = "周一";
                    List monDataList = getDayData(dataMap.get(0), bookRecord);
                    monDataBean = WeekBookData.builder().timer(monDataList).label(dayOfWeekStr).build();
                    break;
                case 2:
                    dayOfWeekStr = "周二";
                    List tueDataList = getDayData(dataMap.get(1), bookRecord);
                    tueDataBean = WeekBookData.builder().timer(tueDataList).label(dayOfWeekStr).build();
                    break;
                case 3:
                    dayOfWeekStr = "周三";
                    List wenDataList = getDayData(dataMap.get(2), bookRecord);
                    wenDataBean = WeekBookData.builder().timer(wenDataList).label(dayOfWeekStr).build();
                    break;
                case 4:
                    dayOfWeekStr = "周四";
                    List thurDataList = getDayData(dataMap.get(3), bookRecord);
                    thurDataBean = WeekBookData.builder().timer(thurDataList).label(dayOfWeekStr).build();
                    break;
                case 5:
                    dayOfWeekStr = "周五";
                    List friDataList = getDayData(dataMap.get(4), bookRecord);
                    friDataBean = WeekBookData.builder().timer(friDataList).label(dayOfWeekStr).build();
                    break;
                case 6:
                    dayOfWeekStr = "周六";
                    List satDataList = getDayData(dataMap.get(5), bookRecord);
                    satDataBean = WeekBookData.builder().timer(satDataList).label(dayOfWeekStr).build();
                    break;
                case 7:
                    dayOfWeekStr = "周日";
                    List sunDataList = getDayData(dataMap.get(6), bookRecord);
                    sunDataBean = WeekBookData.builder().timer(sunDataList).label(dayOfWeekStr).build();
                    break;
            }
        }
        dataList.add(monDataBean);
        dataList.add(tueDataBean);
        dataList.add(wenDataBean);
        dataList.add(thurDataBean);
        dataList.add(friDataBean);
        dataList.add(satDataBean);
        dataList.add(sunDataBean);

        return dataList;
    }


    /**
     * 获取每日预定记录
     *
     * @param dayData
     * @param bookRecord
     */
    private static List<Timer> getDayData(Map<String, String> dayData, Record bookRecord) {
        String[] timeLine = TimeKit.getTimeLine();
        List<Timer> bookDataList = new ArrayList<Timer>();
        for (int i = 0; i < timeLine.length - 1; i++) {
            String timeSlot = timeLine[i] + "-" + timeLine[i + 1];
            if (String.valueOf(dayData.get(timeSlot)) == null ||
                    "null".equals(String.valueOf(dayData.get(timeSlot))) ||
                    "".equals(String.valueOf(dayData.get(timeSlot)))) {
                dayData.put(timeSlot, "暂无");
            }
            if (timeLine[i].equals(bookRecord.get("timeSlot_start"))) {
                dayData.put(timeSlot,
                        "【" + bookRecord.get("book_userDept") + "】-" + bookRecord.get("reason") + "-" + bookRecord.get("book_userName") + "," + bookRecord.get("bookOpenId") + "," + bookRecord.get("status") + "," + bookRecord.get("id"));
                long timeDiff = TimeKit.getTimeDiff(bookRecord.get("timeSlot_start"),
                        bookRecord.get("timeSlot_end"));
                int j;
                for (j = i + 1; j <= i + timeDiff; j++) {
                    dayData.put(timeLine[j] + "-" + timeLine[j + 1],
                            "【" + bookRecord.get("book_userDept") + "】-" + bookRecord.get("reason") + "-" + bookRecord.get("book_userName") + "," + bookRecord.get("bookOpenId") + "," + bookRecord.get("status") + "," + bookRecord.get("id"));
                }
                if (j < timeLine.length - 1)
                    dayData.put(timeLine[j] + "-" + timeLine[j + 1], "暂无");
                i = j;
            }
        }
        for (Map.Entry<String, String> entry : dayData.entrySet()) {
            String bookOpenId = null;
            String doing = entry.getValue();
            String status = null;
            String id = null;
            if (!entry.getValue().equals("暂无")) {
                String[] split = entry.getValue().split(",");
                doing = split[0];
                bookOpenId = split[1];
                status = split[2];
                id = split[3];
            }
            bookDataList.add(Timer.builder().timeLine(entry.getKey()).status(status).doing(doing).openId(bookOpenId).id(id).build());
        }
        Collections.sort(bookDataList, (Timer timer1, Timer timer2) -> {
            if (!StrKit.notNull(timer1) || !StrKit.notNull(timer2))
                throw new HandlerException(ResultEnum.DATA_ERROR, "时间段不合法");
            Long time1 = null, time2 = null;
            try {
                time1 = DateUtil.parse(timer1.getTimeLine().split("-")[0], "HH:mm").getTime();
                time2 = DateUtil.parse(timer2.getTimeLine().split("-")[0], "HH:mm").getTime();
            } catch (Exception e) {
                throw new HandlerException(ResultEnum.DATA_ERROR, "时间段不合法");
            }
            return (int) (time1 - time2);
        });

        return bookDataList;
    }

}
